package top.littlejiang.onlinexam.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.littlejiang.onlinexam.common.base.BasePage;
import top.littlejiang.onlinexam.common.base.BaseServiceImpl;
import top.littlejiang.onlinexam.common.utils.DateUtils;
import top.littlejiang.onlinexam.common.utils.JWTUtils;
import top.littlejiang.onlinexam.entity.OlexamClass;
import top.littlejiang.onlinexam.mapper.OlexamClassMapper;
import top.littlejiang.onlinexam.service.OlexamClassService;
import top.littlejiang.onlinexam.service.OlexamUserService;

import java.util.List;

/**
 * <p>
 * 班级表 服务实现类
 * </p>
 *
 * @author chen
 * @since 2021-03-11
 */
@Service
public class OlexamClassServiceImpl extends BaseServiceImpl<OlexamClassMapper, OlexamClass> implements OlexamClassService {

    @Autowired
    OlexamClassMapper classMapper;
    @Autowired
    OlexamUserService userService;

    /**
     * 分页查询
     *
     * @param page
     * @return IPage<OlexamClass>
     * @author chen
     * @since 2021/3/12 12:11
     */
    @Override
    public IPage<OlexamClass> getClassListPage(BasePage<OlexamClass> page) {
        OlexamClass query = page.getQueryParam();
        QueryWrapper<OlexamClass> wrapper = new QueryWrapper<>();
        wrapper.eq("a.is_del", 0);
        if (!StringUtils.isBlank(query.getClassName())){
            wrapper.like("class_name", query.getClassName());
        }
        if (page.getPageSize() <= 0){
            page.setPageSize(10);
        }
        Page<OlexamClass> p = new Page<>(page.getPageIndex(), page.getPageSize());
        IPage<OlexamClass> pages = classMapper.getClassListPage(p, wrapper);
        return pages;
    }

    /**
     * 更新或增加
     *
     * @param olexamClass
     * @return void
     * @author chen
     * @since 2021/3/12 13:00
     */
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void insertOrUpdate(OlexamClass olexamClass) {
        Integer counsellorId = userService.checkByName(olexamClass.getCounsellorName(), olexamClass.getCounsellorPhone());
        olexamClass.setCounsellorId(counsellorId)
                .setUpdateTime(DateUtils.getTime())
                .setCreateUser(JWTUtils.getUserId());
        saveOrUpdate(olexamClass);
    }

    /**
     * 获取所有未删除值
     * @return
     */
    @Override
    public List<OlexamClass> getAll() {
        QueryWrapper<OlexamClass> wrapper = new QueryWrapper<>();
        wrapper.select("id,class_name")
                .eq("is_del", 0)
                .orderByAsc("class_name");
        return list(wrapper);
    }
}
